//
//  LYCache.m
//  LYNetworkRequestKit
//
//  Created by CPX on 2018/10/23.
//  Copyright © 2018 CPX. All rights reserved.
//

#import "RealmDBManager.h"
#import "YYModel.h"


static NSString *const NetworkResponseCache = @"NetworkResponseCache";


@interface RealmDBManager ()
@property (nonatomic,strong)RLMRealm *realm;

@end

@implementation RealmDBManager

+ (void)initialize {
//    _dataCache = [YYCache cacheWithName:NetworkResponseCache];
}

- (instancetype)share
{
    static RealmDBManager * _instance =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [RealmDBManager new];
        _instance.realm = [RLMRealm defaultRealm];
    });
    return _instance;
}

-(void)addBeadCountWith:(NSString *)proverb_text{
    NSString* current_year = [BeadDBDataModel currentYear];
    NSString* current_month = [BeadDBDataModel currentMonth];
    NSString* current_day = [BeadDBDataModel currentDay];
    BeadDBDataModel * obj = [self getCurrentProverbObj:proverb_text year:current_year month:current_month day:current_day];
    obj.count++;

    [self.realm beginWriteTransaction];
    [self.realm addOrUpdateObject:obj];
    [self.realm commitWriteTransaction];
}

- (void)deleteBeadObject:(BeadDBDataModel *)obj{
    [self.realm beginWriteTransaction];
    [self.realm deleteObject:obj];
    [self.realm commitWriteTransaction];
}

- (void)deleteAllObjects{
    [self.realm beginWriteTransaction];
    [self.realm deleteAllObjects];
    [self.realm commitWriteTransaction];
}
-(RLMResults <BeadDBDataModel*>  *)getAllObject{
    RLMResults *results = [BeadDBDataModel allObjects];
    return results;
}
-(BeadDBDataModel*)getCurrentProverbObj:(NSString *)proverb_text
                                                  year:(NSString* )year
                                                   month:(NSString * )month
                                                    day:(NSString *)day{
    //默认从数据库查询、如果没有生成一条返回
    NSString * sqlString = [NSString stringWithFormat:@"proverb_text = %@ AND year = %@ AND month = %@ AND day = %@",proverb_text,year,month,day];
    RLMResults <BeadDBDataModel * >  *  results = [BeadDBDataModel objectsWhere:sqlString];
    if (results.count){
        return results.firstObject;
    }
    BeadDBDataModel * data = [[BeadDBDataModel alloc]init];
    data.proverb_text = proverb_text;
    data.year = year;
    data.month = month;
    data.day = day;
    data.count = 1;
    data.time_stamp = [BeadDBDataModel currentTimeInterval];
  
    return data;

    
}

-(NSArray <DateSortedModel*>* )getByYear{
    RLMResults *results  = [self getAllObject];
    if (!results.count){
        return nil;
    }
    NSArray *  yearData  = [self getByYear];
    
    NSMutableArray *timeArr=[NSMutableArray array];
    for (NSInteger index = 0;index<results.count;index++){//去除所有年份
        BeadDBDataModel* obj = results[index];
        [timeArr addObject:obj.year];
    }
    //使用asset把timeArr的日期去重
    NSSet *set = [NSSet setWithArray:timeArr];
    NSArray *useArray = [set allObjects];
    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列，no,降序排列
    
    //按日期降序排列的日期数组
    NSArray *myary = [useArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    NSMutableArray * returnArray = [NSMutableArray array];
    for (NSString * year in myary) {
        DateSortedModel * model = [[DateSortedModel alloc]init];
        NSMutableArray * beads  = [NSMutableArray new];
        for (NSInteger index = 0;index<results.count;index++){//去除所有年份
            BeadDBDataModel* obj = results[index];
            if ([year isEqualToString:obj.year]){
                model.year = year;
                model.title = year;
                [beads addObject:obj];
            }
        }
        model.BeadLogArray = beads;
        [returnArray addObject:model];
    }
    return returnArray;


    
}

-(NSArray <DateSortedModel*>* )getByMonth{
    RLMResults *results  = [self getAllObject];
    if (!results.count){
        return nil;
    }
    NSMutableArray *timeArr=[NSMutableArray array];
    for (NSInteger index = 0;index<results.count;index++){//去除所有年份
        BeadDBDataModel* obj = results[index];
        [timeArr addObject:[NSString stringWithFormat:@"%@/%@",obj.year,obj.month]];
    }
    //使用asset把timeArr的日期去重
    NSSet *set = [NSSet setWithArray:timeArr];
    NSArray *useArray = [set allObjects];
    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列，no,降序排列
    
    //按日期降序排列的日期数组
    NSArray *myary = [useArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    NSMutableArray * returnArray = [NSMutableArray array];
    for (NSString * yeadandmonth in myary) {
        DateSortedModel * model = [[DateSortedModel alloc]init];
        NSMutableArray * beads  = [NSMutableArray new];
        for (NSInteger index = 0;index<results.count;index++){//去除所有年份
            BeadDBDataModel* obj = results[index];
            if ([yeadandmonth isEqualToString:[NSString stringWithFormat:@"%@/%@",obj.year,obj.month]]){
                model.year = obj.year;
                model.month = obj.month;
                model.title = yeadandmonth;
                [beads addObject:obj];
            }
        }
        model.BeadLogArray = beads;
        [returnArray addObject:model];
    }
    return returnArray;

}

-(NSArray <DateSortedModel*>* )getByday{
    RLMResults *results  = [self getAllObject];
    if (!results.count){
        return nil;
    }
    NSMutableArray *timeArr=[NSMutableArray array];
    for (NSInteger index = 0;index<results.count;index++){//去除所有年份
        BeadDBDataModel* obj = results[index];
        [timeArr addObject:[NSString stringWithFormat:@"%@/%@/%@",obj.year,obj.month,obj.day]];
    }
    //使用asset把timeArr的日期去重
    NSSet *set = [NSSet setWithArray:timeArr];
    NSArray *useArray = [set allObjects];
    NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列，no,降序排列
    
    //按日期降序排列的日期数组
    NSArray *myary = [useArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
    NSMutableArray * returnArray = [NSMutableArray array];
    for (NSString * yeadandmonthandday in myary) {
        DateSortedModel * model = [[DateSortedModel alloc]init];
        NSMutableArray * beads  = [NSMutableArray new];
        for (NSInteger index = 0;index<results.count;index++){//去除所有年份
            BeadDBDataModel* obj = results[index];
            if ([yeadandmonthandday isEqualToString:[NSString stringWithFormat:@"%@/%@/%@",obj.year,obj.month,obj.day]]){
                model.year = obj.year;
                model.month = obj.month;
                model.day = obj.day;
                model.title  = yeadandmonthandday;
                [beads addObject:obj];
            }
        }
        model.BeadLogArray = beads;
        [returnArray addObject:model];
    }
    return returnArray;
}



@end



@implementation BeadDBDataModel

static  NSDateFormatter * formatter;
static NSCalendar *calendar;
+(NSString * _Nonnull)currentTimeInterval{
    if (formatter == nil){
        formatter  = [[NSDateFormatter alloc ] init];
    }
    
    [formatter setDateFormat:@"YYYYMMddhhmmssSSS"];
    NSString * date = [formatter stringFromDate:[NSDate date]];
    NSString *  timeNow = [[NSString alloc] initWithFormat:@"%@", date];
 
    return timeNow;
}
+ (NSString *)currentYear{
    if (calendar == nil){
        calendar  = [NSCalendar currentCalendar];
    }
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger year =[dateComponent year];
    return [NSString stringWithFormat:@"%ld",year];
}
+ (NSString *)currentMonth{
    if (calendar == nil){
        calendar  = [NSCalendar currentCalendar];
    }
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger month =[dateComponent month];
    return [NSString stringWithFormat:@"%ld",month];

}
+ (NSString *)currentDay{
    if (calendar == nil){
        calendar  = [NSCalendar currentCalendar];
    }
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    NSInteger day =[dateComponent day];
    return [NSString stringWithFormat:@"%ld",day];
}
//主键
+ (NSString *)primaryKey {
    return @"time_stamp";
}


@end


@implementation DateSortedModel


@end
